package com.baselibrary.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.media.ExifInterface;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;

import com.baselibrary.MessageBus;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class BitmapUtils {
    public static long maxFileSize = 1024 * 1024;
    private static BitmapFactory.Options options = null;
    /**
     * 判断图片是否已经损坏
     */
    public static boolean getEffective(String path) {
        if (options == null) {
            options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
        }
        BitmapFactory.decodeFile(path, options); //filePath代表图片路径
        if (options.mCancel || options.outWidth == -1
                || options.outHeight == -1) {
            //表示图片已损毁
            return false;
        }
        return true;
    }

    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

    public static int calculateInSampleSize(Bitmap bitmap, int reqWidth, int reqHeight) {
        final int picheight = bitmap.getHeight();
        final int picwidth = bitmap.getWidth();

        int targetheight = picheight;
        int targetwidth = picwidth;
        int inSampleSize = 1;

        if (targetheight > reqHeight || targetwidth > reqWidth) {
            while (targetheight >= reqHeight && targetwidth >= reqWidth) {
                inSampleSize += 1;
                targetheight = picheight / inSampleSize;
                targetwidth = picwidth / inSampleSize;
            }
        }
        return inSampleSize;
    }

    public static int getBitmapDegree(String path) {
        int degree = 0;
        int orientation;
        try {
            orientation = new ExifInterface(path).getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);
        } catch (IOException e) {
//            Log.e(TAG, "getBitmapDegree: ", e);
            orientation = 0;
        }
        if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
            degree = 90;
        } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
            degree = 180;
        } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
            degree = 270;
        }
        return degree;
    }

    public static String getAppPath(Context context) {
        String root = Environment.getExternalStorageDirectory().getAbsolutePath();
        String dirName = "hanKe";
        File appDir = new File(root, dirName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        return appDir.getAbsolutePath();
    }

    /**
     * 先测量和布局，再生成Bitmap
     */
    public static Bitmap convertViewToBitmap(View view) {
        int width = view.getMeasuredWidth();
        int height = view.getMeasuredHeight();
        return convertViewToBitmap(view, width, height);
    }

    public static Bitmap convertViewToBitmap(View view, int width, int height) {
        Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bmp);
        view.draw(canvas);
        return bmp;

    }


    public static void qualityCompress(Context context, File fromFie, File tagFile) {
        try {
            if (!fromFie.exists()) {
                EventBusUtils.sendNotify1Value(MessageBus.msgid_notify_total_status, "发布失败");
                ToastUtils.showShort(context, "图片源文件未找到");
                return;
            }
            if (fromFie.length() > maxFileSize) {
                //大于3MB
                FileInputStream fis = new FileInputStream(fromFie);
                Bitmap bmp = BitmapFactory.decodeStream(fis);
                if (bmp != null) {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    int options = 70;//个人喜欢从80开始,
                    bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
                    while (baos.toByteArray().length > maxFileSize) {
                        //1MB
                        baos.reset();
                        options -= 10;
                        bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
                    }
                    FileOutputStream fos = new FileOutputStream(tagFile);
                    fos.write(baos.toByteArray());
                    fos.flush();
                    fos.close();
                }
            } else {
                FileUtils.copySdcardFile(fromFie, tagFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Bitmap addWatermarkImg(Context context, String path, String userName) {
        if (TextUtils.isEmpty(userName))
            userName = "";
        float testSize = 13;
        float paddingRight = 20;
        float paddingBottom = 20;
        Bitmap bitmap = null;
        int bitmapDegree = BitmapUtils.getBitmapDegree(path);
        if (bitmapDegree > 0) {
            bitmap = BitmapUtils.rotaingImageView(bitmapDegree, BitmapFactory.decodeFile(path));
        } else {
            bitmap = BitmapFactory.decodeFile(path);
        }
        int screenHeight = ScreenUtils.getScreenHeight(context);
        int screenWidth = ScreenUtils.getScreenWidth(context);
        int bitWidth = bitmap.getWidth();
        int bitHeight = bitmap.getHeight();
        float mScale = Math.max((float) bitWidth / screenWidth, (float) bitHeight / screenHeight);
        testSize = mScale * 16;
        paddingRight = mScale * 16;
        paddingBottom = mScale * 20;
        return ImageUtil.drawTextToRightBottom(context, bitmap, "酣享@" + userName, testSize, Color.WHITE, paddingRight, paddingBottom);
    }


    /**
     * 读取照片旋转角度
     *
     * @param path 照片路径
     * @return 角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 旋转图片
     *
     * @param angle  被旋转角度
     * @param bitmap 图片对象
     * @return 旋转后的图片
     */
    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        Bitmap returnBm = null;
        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        }
        if (returnBm == null) {
            returnBm = bitmap;
        }
        if (bitmap != returnBm) {
            bitmap.recycle();
        }
        return returnBm;
    }
    public static Bitmap createView(String text) {
        //创建了一个 400*400 的 ARGB_8888 类型的空白位图对象
        Bitmap bitmap = Bitmap.createBitmap(300, 200, Bitmap.Config.ARGB_8888);
        //创建画布对象
        Canvas canvas = new Canvas(bitmap);
        //绘制文字
        Paint paint = new Paint();
        // 防锯齿
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.FILL);
        //设置文本的对齐方式，可选值有 Paint.Align.LEFT、Paint.Align.CENTER、Paint.Align.RIGHT
        //等。
        paint.setTextAlign(Paint.Align.LEFT);
        int sp = ScreenUtils.dpToPx(11);
        //设置文本大小，单位是 px，这个和我们平时使用的字体单位 sp 不同，所以最好进行转
        //换。
        paint.setTextSize(sp);
        paint.setColor(Color.parseColor("#FFFFFF"));
        //设置文本的倾斜程度，skewx 取值于 0~1 之间，正负表示倾斜的方向 正表示向左倾斜。
        paint.setTextSkewX(0f);
        //设置文本的粗体样式，bold 为 true 表示粗体。
        canvas.drawText(SpanUtils.appendEllipsis(text,8), 0, 130, paint);
        return bitmap;
    }

    // 按大小缩放
    public static Bitmap getImageCompress(final String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        // 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 800f;// 这里设置高度为800f
        float ww = 480f;// 这里设置宽度为480f
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;// 设置缩放比例
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
    }

    // 图片质量压缩
    private static Bitmap compressImage(Bitmap image) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
            int options = 100;

            while (baos.toByteArray().length / 1024 > 1024*5) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
                baos.reset();// 重置baos即清空baos
                image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
                options -= 10;// 每次都减少10
                System.out.println("options--->" + options + "    "
                        + (baos.toByteArray().length / 1024));
            }
            ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
            Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
